package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.common.api.Response;
import com.cw.common.constant.Constants;
import com.cw.common.method.SendCardMsg;
import com.cw.entity.*;
import com.cw.mapper2.*;
import com.cw.service.IPatientBedMiddleRjssService;
import com.cw.util.HttpUtil;
import com.cw.util.UUIDUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-05-09
 */
@Service
//@Transactional(rollbackFor = Exception.class, timeout = 5)
public class PatientBedMiddleRjssServiceImpl extends ServiceImpl<PatientBedMiddleRjssMapper, PatientBedMiddleRjss> implements IPatientBedMiddleRjssService {

    @Autowired
    private ThisIiPrepayinMapper thisIiPrepayinMapper;
    private static ReentrantLock lock = new ReentrantLock();

    @Autowired
    private HisCwglBedMapper hisCwglBedMapper;

    @Autowired
    private ApplicationBedMapper applicationBedMapper;


    @Override
    public List<PatientBedMiddleRjss> getAllRegisterBeds() {
        return baseMapper.getRegisterBedByBedIds(null, null);
    }

    /**
     * 日间病房床位登记
     *
     * @param bedId
     * @param patientId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addPatientBed(String bedId, String patientId) {

        lock.lock();
        try {
            //判断是否被预约
            List<PatientBedMiddleRjss> patientBedNew = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddleRjss()).eq(PatientBedMiddleRjss::getBedNo, bedId).eq(PatientBedMiddleRjss::getState, "1"));
            if (CollectionUtils.isNotEmpty(patientBedNew)) {
                return new Response(500, "床位预约失败,该床已被占用");
            }
            //判断预约患者者是否 0取消预约2转入院3出院9作废
            //获取患者信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            if ("0".equals(thisIiPrepayin.getPreState())) {
                return new Response(500, "床位预约失败，该患者电子住院证已取消");
            }
            else if ("1".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已预约床位");
            }
            else if ("2".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已入院");
            }
            else if ("3".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者已出院");
            }
            else if ("9".equals(thisIiPrepayin.getRegisteStatus())) {
                return new Response(500, "床位预约失败，该患者电子住院证已作废");
            }
            else {

            }
            //根据床位编码获取床位信息
            HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, bedId)).get(0);
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);
            //根据病人PreId获取病人信息
            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(patientId);
            //根据病人PreId获取电子一体化床位申请信息
            PatientBedMiddleRjss patientBed = new PatientBedMiddleRjss();
            patientBed.setId(UUIDUtil.uuid());
            patientBed.setBedNo(bedId);
            patientBed.setIdenno(thisIiPrepayin.getIdenno());
            patientBed.setPreid(thisIiPrepayin.getPreid());
            patientBed.setYard(hisCwglBed.getYard());
            patientBed.setNurseCellCode(hisCwglBed.getNurseCellCode());
            patientBed.setNurseCellName(hisCwglBed.getNurseCellName());
            patientBed.setNurseCellCodeBefore(thisIiPrepayin.getNurseCellCode());
            patientBed.setDeptCode(hisCwglBed.getDeptCode());
            patientBed.setDeptName(hisCwglBed.getDeptName());
            patientBed.setState("1");//已预约
            patientBed.setOperNo(userId);
            patientBed.setOpenName(userName);
            patientBed.setOperTime(LocalDateTime.now());
            //如果电子住院证中有住院号,将住院号回写至预约表(先去住院处登记的情况)
            patientBed.setInpatientNo(patientInfo.getInpatientNo());
            Integer insert = baseMapper.insert(patientBed);
            //修改预约表信息
            // 预约状态 0 未预约   1已预约
            thisIiPrepayin.setRegisteStatus("1");
            thisIiPrepayin.setNurseCellCode(hisCwglBed.getNurseCellCode());
            thisIiPrepayin.setBedNo(hisCwglBed.getBedNo());
            Integer update = thisIiPrepayinMapper.updateById(thisIiPrepayin);
        } catch (Exception e) {
            return new Response(500, "床位预约失败");
        } finally {
            lock.unlock();
        }
        return new Response(200, "床位预约成功");

    }


    /**
     * 取消预约
     *
     * @param bedId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response delPatientBed(String bedId, String patientId) {
        try {
            ThisIiPrepayin patientInfo = thisIiPrepayinMapper.selectById(patientId);
            HisCwglBed hisCwglBed = hisCwglBedMapper.selectList(new LambdaQueryWrapper<>(new HisCwglBed()).eq(HisCwglBed::getBedNo, bedId)).get(0);
            //根据病人PreId获取电子一体化床位申请信息
            ApplicationBed applicationBed = applicationBedMapper.selectById(patientId);
            String userName = HttpUtil.getRequestHeaderInfo(Constants.USER_NAME);
            String userId = HttpUtil.getRequestHeaderInfo(Constants.USER_ID);
            String realName = HttpUtil.getRequestHeaderInfo("realname");
            //更改状态为取消登记 4 取消登记
            //根据床位id和患者id获取中间表信息
            List<PatientBedMiddleRjss> patientBedMiddles = baseMapper.selectList(new LambdaQueryWrapper<>(new PatientBedMiddleRjss()).eq(PatientBedMiddleRjss::getBedNo, bedId).eq(PatientBedMiddleRjss::getPreid, patientId).eq(PatientBedMiddleRjss::getState, "1"));
            if (CollectionUtils.isEmpty(patientBedMiddles) || patientBedMiddles.size() != 1) {
                return new Response(500, "取消失败，该患者没有已预约的床位");
            }
            PatientBedMiddleRjss patientBedMiddle = patientBedMiddles.get(0);
            //修改状态
            patientBedMiddle.setState("4");
            patientBedMiddle.setOperNo(userId);
            patientBedMiddle.setOpenName(userName);
            patientBedMiddle.setOperTime(LocalDateTime.now());
            Integer del = baseMapper.updateById(patientBedMiddle);
            //获取该患者预约表信息
            ThisIiPrepayin thisIiPrepayin = thisIiPrepayinMapper.selectById(patientId);
            //修改预约表状态
            thisIiPrepayin.setRegisteStatus("0");
            thisIiPrepayin.setBedNo("");
            thisIiPrepayin.setNurseCellCode(patientBedMiddle.getNurseCellCodeBefore());
            Integer update = thisIiPrepayinMapper.updateById(thisIiPrepayin);
        } catch (Exception ex) {
            int a =0;
        }
        return new Response(200, "取消成功");
    }

}
